import * as echarts from 'echarts'

function hexToRgba(hex, opacity) {
  let rgbaColor = ""
  let reg = /^#[\da-f]{6}$/i
  if (reg.test(hex)) {
    rgbaColor = `rgba(${parseInt("0x" + hex.slice(1, 3))},${parseInt(
      "0x" + hex.slice(3, 5)
    )},${parseInt("0x" + hex.slice(5, 7))},${opacity})`
  }
  return rgbaColor
}

function rgbaToHex(rgba) {
  // 将 rgba(79,191,227,1) 转换为 #4fbbe3
  const match = rgba.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/)
  if (match) {
    const r = parseInt(match[1]).toString(16).padStart(2, '0')
    const g = parseInt(match[2]).toString(16).padStart(2, '0')
    const b = parseInt(match[3]).toString(16).padStart(2, '0')
    return `#${r}${g}${b}`
  }
  return '#4fbbe3' // 默认颜色
}

// 格式化数字：千用k，万用10k，十万用零点几M，百万用1M
function formatNumber(num) {
  if (num >= 1000000) {
    // 百万及以上：如 1M, 1.5M
    const millions = (num / 1000000).toFixed(1)
    return millions % 1 === 0 ? `${Math.floor(millions)}M` : `${millions}M`
  } else if (num >= 100000) {
    // 十万：如 0.5M, 0.8M
    const millions = (num / 1000000).toFixed(1)
    return `${millions}M`
  } else if (num >= 10000) {
    // 万：如 10k, 25k
    const thousands = (num / 1000).toFixed(0)
    return `${thousands}k`
  } else if (num >= 1000) {
    // 千：如 1k, 5k
    const thousands = (num / 1000).toFixed(1)
    return thousands % 1 === 0 ? `${Math.floor(thousands)}k` : `${thousands}k`
  }
  return num.toString()
}

export function createChartOption(timeLabels, seriesData, fishingGrounds, colors) {
  // 创建 series 配置
  const series = seriesData.map((item, index) => {
    const hexColor = rgbaToHex(item.itemStyle.color || colors[index])
    
    return {
      name: item.name,
      type: 'line',
      smooth: true,
      symbol: 'circle',
      symbolSize: 5,
      showSymbol: false,
      lineStyle: {
        width: 1.5,
        color: item.lineStyle?.color || colors[index]
      },
      itemStyle: {
        color: item.itemStyle?.color || colors[index]
      },
      areaStyle: {
        color: new echarts.graphic.LinearGradient(
          0, 0, 0, 1,
          [
            { offset: 0, color: hexToRgba(hexColor, 0.3) },
            { offset: 1, color: hexToRgba(hexColor, 0) }
          ],
          false
        )
      },
      data: item.data || [],
      emphasis: {
        focus: 'series'
      }
    }
  })

  return {
    color: colors,
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(28, 46, 81, 0.8)',
      borderColor: 'rgba(44, 81, 153, 1)',
      borderWidth: 1,
      textStyle: {
        color: '#fff',
        fontSize: 12
      },
      // 固定tooltip位置在右侧，避免被遮挡
      position: function(point, params, dom, rect, size) {
        // point: 鼠标位置
        // params: tooltip参数
        // dom: tooltip的DOM元素
        // rect: 图表容器的位置和大小
        // size: tooltip的宽高
        const [x, y] = point
        const viewWidth = size.viewSize[0]
        const tooltipWidth = size.contentSize[0]
        
        // 如果鼠标在左侧1/3区域，tooltip显示在右侧
        if (x < viewWidth / 3) {
          return [viewWidth * 0.65, y - size.contentSize[1] / 2]
        }
        // 否则显示在鼠标右侧
        return [x + 10, y - size.contentSize[1] / 2]
      },
      formatter: function(params) {
        let html = `<div style="color: #fff; font-size: 14px; line-height: 24px; padding-bottom: 5px; border-bottom: 1px solid rgba(255,255,255,0.3); margin-bottom: 5px;">
          ${params[0].axisValue}
        </div>`
        params.forEach(param => {
          const color = param.color
          const formattedValue = formatNumber(param.value)
          html += `<div style="color: #fff; font-size: 12px; line-height: 24px; display: flex; align-items: center;">
            <span style="display:inline-block; margin-right: 8px; border-radius: 50%; width: 10px; height: 10px; background-color: ${color};"></span>
            ${param.seriesName}: 
            <span style="color: ${color}; font-weight: 700; font-size: 14px; margin-left: 5px;">${formattedValue} 吨</span>
          </div>`
        })
        return html
      },
      axisPointer: {
        type: 'line',
        lineStyle: {
          color: 'rgba(255, 255, 255, 0.3)',
          type: 'dashed'
        }
      }
    },
    legend: {
      show: false
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '5%',
      top: '5%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: timeLabels,
      axisLine: {
        lineStyle: {
          color: 'rgba(44, 81, 153, 1)'
        }
      },
      axisLabel: {
        color: '#bddbf1',
        fontSize: 10,
        rotate: timeLabels.length > 7 ? 45 : 0,
        interval: timeLabels.length > 15 ? 'auto' : 0
      },
      axisTick: {
        show: false
      },
      splitLine: {
        show: false
      }
    },
    yAxis: {
      type: 'value',
      name: '捕捞量(吨)',
      nameTextStyle: {
        color: '#bddbf1',
        fontSize: 10,
        padding: [0, 0, 0, 8]
      },
      axisLine: {
        show: false
      },
      axisTick: {
        show: false
      },
      axisLabel: {
        color: '#bddbf1',
        fontSize: 10
      },
      splitLine: {
        lineStyle: {
          color: 'rgba(44, 81, 153, 0.5)',
          type: 'dashed'
        }
      }
    },
    series: series,
    dataZoom: timeLabels.length > 15 ? [{
      type: 'slider',
      show: true,
      xAxisIndex: [0],
      bottom: '5%',
      height: 20,
      handleStyle: {
        color: 'rgba(79, 191, 227, 0.8)'
      },
      textStyle: {
        color: '#bddbf1'
      },
      borderColor: 'rgba(44, 81, 153, 1)'
    }] : []
  }
}

